package git.soulbgm.service.impl;

import git.soulbgm.common.base.BaseServiceImpl;
import git.soulbgm.mapper.OrderMapper;
import git.soulbgm.pojo.AccountDto;
import git.soulbgm.pojo.GoodsDto;
import git.soulbgm.pojo.OrderDto;
import git.soulbgm.pojo.Orders;
import git.soulbgm.service.AccountServiceFeignClient;
import git.soulbgm.service.GoodsServiceFeignClient;
import git.soulbgm.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 订单表
 *
 * @author SoulBGM
 * @version V1.0
 * @date 2020-11-06 17:27:16
 */
@Service
public class OrderServiceImpl extends BaseServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private AccountServiceFeignClient accountService;

    @Autowired
    private GoodsServiceFeignClient goodsService;


    @GlobalTransactional
    @Override
    public Long createOrder(OrderDto dto) throws Exception {
        // 扣减库存
        Boolean result = goodsService.reduceInventory(GoodsDto.builder().goodsId(dto.getGoodsId()).amount(dto.getAmount()).build());
        if (!result) {
            throw new Exception("扣除库存失败");
        }
        // 扣减余额
        result = accountService.reduceBalance(AccountDto.builder().accountId(dto.getAccountId()).price(dto.getPrice()).build());
        if (!result) {
            throw new Exception("扣除余额失败");
        }
        // 保存订单
        Orders orders = new Orders();
        orders.setAccountId(dto.getAccountId());
        orders.setGoodsId(dto.getGoodsId());
        orders.setPayAmount(dto.getPrice());
        orders.setCreateTime(new Date());
        orders.setStatus(0);
        result = save(orders);
        // 返回订单编号
        if (result) {
            return orders.getId();
        }
        return 0L;
    }

}